package club.banyuan.video;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class VideoStore implements Serializable {

    private List<Video> videos = new ArrayList<>();
    private int count;

    public List<Video> getVideos() {
        return videos;
    }

    public void setVideos(List<Video> videos) {
        this.videos = videos;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    // 从文件加载内容
    // JsonSerial
//    public static VideoStore load() {
//        String filePath = PropUtil.getProp("store.file.path");
//        File file = new File(filePath);
//        if (!file.exists()){
//            File newFile = new File(file.getParent());
//            newFile.mkdirs();
//        }
//        try (InputStream inputStream = new FileInputStream(filePath)) {
//
//            return JSONObject
//                    .parseObject(inputStream, StandardCharsets.UTF_8, VideoStore.class);
//
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return new VideoStore();
//    }

    // ObjectSerial
    public static VideoStore load() {
        String filePath = PropUtil.getProp("store.file.path");
        checkFileExist(filePath);
        try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(filePath))) {
            Object o = objectInputStream.readObject();
            return (VideoStore) o;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return new VideoStore();
    }


    // JsonSerial
//    public void save() {
//        String filePath = PropUtil.getProp("store.file.path");
//        checkFileExist(filePath);
//        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
//            writer.write(JSONObject.toJSONString(this));
//            writer.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    // ObjectSerial
    public void save() {
        String filePath = PropUtil.getProp("store.file.path");
        checkFileExist(filePath);
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath))) {
            objectOutputStream.writeObject(this);
            objectOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加一个新的电影
     * 通过电影的名称创建一个video对象，将对象保存在数组中
     *
     * @param name 电影的名称
     */
    public void addVideo(String name) {
        if (count >= Integer.parseInt(PropUtil.getProp("size"))) {
            System.out.println("装不下,操作失败");
            return;
        }
        Video v1 = new Video();
        v1.setName(name);
        videos.add(v1);
        System.out.println("操作成功");
        count++;
    }

    /**
     * 根据片名借出电影
     *
     * @return 成功借出电影，返回true,如果片名不存在，则返回false
     */
    public boolean checkOut(String videoName) {
        Video video = findVideoByName(videoName);
        if (video != null && video.isRent()) {
            System.out.println("电影已经被借出");
            video.setRent(true);
            return false;
        } else if (video != null && !video.isRent()) {
            video.setRent(true);
            return true;
        }
        return false;
    }

    /**
     * 归还电影
     *
     * @return 成功归还电影，返回true,如果片名不存在，则返回false
     */
    public boolean returnVideo(String videoName) {
        Video video = findVideoByName(videoName);
        if (video != null && video.isRent()) {
            video.setRent(false);
            return true;
        } else if (video != null && !video.isRent()) {
            System.out.println("电影未借出");
            video.setRent(false);
            return false;
        }
        return false;
    }

    /**
     * 根据 电影名称查询电影
     *
     * @param videoName
     * @return 匹配到的电影，如果找不到对应名称的电影，返回null
     */
    private Video findVideoByName(String videoName) {
        for (int i = 0; i < count; i++) {
            if (videoName.equals(videos.get(i).getName())) {
                return videos.get(i);
            }
        }
        System.out.println("没有这个电影：" + videoName);
        return null;
    }

    /**
     * 设置用户对电影的评分(1~5)，收到评分之后，计算该电影的平均评分，
     */
    public void receiveRating(String videoName, int mark) {
        Video videoByName = findVideoByName(videoName);
        if (videoByName != null) {
            videoByName.setMark(mark);
        }
    }

    /**
     * 列出整个库存的电影。
     * 电影名称  是否被借出   平均评分
     */
    public void listInventory() {
        for (int i = 0; i < count; i++) {
            String rentMsg = "没有被借出";
            if (videos.get(i).isRent()) {
                rentMsg = "已被借出";
            }
            System.out.println("电影名称是" + videos.get(i).getName() + rentMsg + "平均评分为" + videos.get(i).getMark());
        }
    }

    // public static void main(String[] args) {
    //   VideoStore videoStore = new VideoStore();
    //   videoStore.addVideo("黑客帝国");
    //   videoStore.addVideo("教父");
    //   videoStore.addVideo("沉默的羔羊");
    //   videoStore.listInventory();
    //   videoStore.checkOut("教父");
    //   videoStore.listInventory();
    //   videoStore.returnVideo("教父");
    //   videoStore.receiveRating("教父", 4);
    //   videoStore.listInventory();
    //
    // }

    public void addVideo() {
        System.out.println("要添加的电影名称：");
        Scanner scanner = new Scanner(System.in);
        String videoName = scanner.nextLine();
        addVideo(videoName);
        save();
    }

    // TODO 借出电影
    public void checkOut() {
        System.out.println("要借出的电影名称：");
        Scanner scanner = new Scanner(System.in);
        String videoName = scanner.nextLine();
        if (checkOut(videoName)) {
            System.out.println("操作成功");
        } else {
            System.out.println("操作失败");
        }

        save();
    }

    // TODO 归还电影
    public void returnVideo() {
        System.out.println("要归还的电影名称：");
        Scanner scanner = new Scanner(System.in);
        String videoName = scanner.nextLine();
//        returnVideo(videoName);
        if (returnVideo(videoName)) {
            System.out.println("请给电影评分（0～5）：");
        } else {
            System.out.println("操作失败");
        }

        int mark = scanner.nextInt();
        receiveRating(videoName, mark);
        save();
    }

    // 判断文件是否存在,不存在就创建
    private static void checkFileExist(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            File newFile = new File(file.getParent());
            newFile.mkdirs();
        }
    }

//  public static void main(String[] args) throws IOException {
//    File file = new File("~/Desktop/123.txt");
//
//    System.out.println(file.getAbsolutePath());
//     FileOutputStream fileOutputStream = new FileOutputStream("~/Desktop/123.txt");
//     fileOutputStream.write(1);
//     fileOutputStream.close();
//     try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("~/Desktop/123.txt")))) {
//       writer.write(JSONObject.toJSONString(new Object()));
//       writer.flush();
//     } catch (IOException e) {
//       e.printStackTrace();
//     }
//  }
}
